# -*- coding: utf-8 -*-
#
# Author:: Jonny
# Date:: 2020/12/12
import os
from time import sleep

from submodules.common.lib.platform_ import is_windows, is_mac
from lib.log_ import logger


def get_pid_by_port(port):
    '''

    :param port: "4723"
    :return: ['14020', '14020', '10836']
    '''
    pid_list = []

    if is_windows():
        res = os.popen('netstat -aon|findstr ":%s"' % str(port)).readlines()
        # TCP    0.0.0.0:4724           0.0.0.0:0              LISTENING       12120
        for item in res:
            item = item.strip("\n").split(" ")
            # windows pid有时候会有0？
            if item[-1] != "0":
                pid_list.append(item[-1])
    if is_mac():
        res = os.popen("lsof -i:%s | awk '{print $2}' | grep -v 'PID'" % str(port)).readlines()
        for item in res:
            item = item.strip("\n").split(" ")
            pid_list.append(item[0])
    logger.info("pid_list:%s" % pid_list)
    # windows pid有时候会有重复
    pid_list = list(set(pid_list))
    return pid_list


def kill_process_by_port(port):
    is_killed = False

    if is_windows():
        pid_list = get_pid_by_port(port)
        pid_list.sort()
        for item in pid_list:
            r = os.popen("taskkill /f /pid %s" % item)
            r.close()
        for i in range(10):
            if get_pid_by_port(port) == []:
                is_killed = True
                break
            sleep(1)

    if is_mac():
        # while get_pid_by_port(port) != []:
        #     pid_list = get_pid_by_port(port)
        #     pid_list.sort()
        #     for item in pid_list:
        #         r = os.popen("taskkill /f /pid %s" % item)
        #         r.close()
        #     sleep(1)

        cmd = "for i in `lsof -i:%s | awk '{print $2}' | grep -v 'PID'`;do kill -9 $i;done" % port
        r = os.popen(cmd)
        r.close()
        for i in range(10):
            if get_pid_by_port(port) == []:
                is_killed = True
                break
            sleep(1)
    return is_killed


if __name__ == "__main__":
    # kill_process_by_port(4724)
    res = get_pid_by_port(4724)
    print(res)
# D:/code/auto-test-microapp/scripts/bat/star_appium.bat
